<template>
	<view class="editor">
		<editor-header @back="back"
				@save="submit()"
		></editor-header>
		<view class="content px-1">
			<!-- 图片 -->
			<view class="ablum flex m-1 mr-0">
				<u-scroll-list :indicator="false">
				    <view class="block" v-for="(item, index) in uploadedImageList" :key="index"
						:class="{
							cover: coverPath == item
						}"
						@click="picTap(item, index)"
					>
						<block v-if="coverPath == item">
							<view class="tag">封面</view>
							<image class="img"
									:src="item"
							></image>
						</block>
						<block v-else>
							<image class="img_nomal"
									:src="item"
							></image>
						</block>
					</view>
				    <view class="add flex justify-center align-center"
						@click="chooseIamge()"
						v-if="note.pictures.length < 20"
					>
				    	+
				    </view>
				</u-scroll-list>
			</view>
			<!-- 标题 -->
			<view class="title">
				<u--textarea v-model="note.title" 
					placeholder="请输入1~95字符的标题" 
					autoHeight
					:maxlength="95"
					border="none"
				></u--textarea>
			</view>
			<!-- 内容 -->
			<view class="content">
				<u--textarea v-model="note.content"
					placeholder="您此刻想记录..." 
					autoHeight
					:maxlength="65000"
					border="none"
					placeholderClass="myTextarea"
				></u--textarea>
			</view>
			<view class="category">
				<view class="category_title mt-1 px-1 py-2"  @click="category.show = true">
					<view class="select">
						<view class="left">您需要发布到</view>
						<view class="right" v-if="selectCategoryList.length == 0">
							<u-icon name="arrow-right" 
									color="#8d8d8d" 
									size="30">
							</u-icon>
						</view>
					</view>
					<view class="tags" v-if="selectCategoryList.length != 0">
						<text class="tag text-center ml-2 px-1 mb-1 rounded-md"
								v-for="(item, index) in selectCategoryList" :key="index"
						>
							#{{item.name}}
						</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 弹窗 -->
		<u-modal :show="modal.showModal" :title="modal.title" 
			:showCancelButton="true"
			:cancelColor="modal.cancelColor"
			@cancel="cancel"
			@confirm="confirm"
		>
			<view class="slot-content">
				<u--input
					placeholder="请输入草稿箱标题"
					border="surround"
					clearable
					v-model="modal.text"
					@change="inputChange()"
				></u--input>
				<view class="error" v-if="modal.errorShow">
					亲，请输入草稿箱标题哦！~
				</view>
			</view>
		</u-modal>
		<!-- 选择分类弹窗 --> 
		<u-popup :show="category.show" :round="35" @close="category.show = false">
			<view class="popup py-2">
				<view class="close">
					<view class="icon mr-2 mb-2">
						<u-icon name="close" color="#676767" 
								size="50"
								@click="category.show = false"
						></u-icon>
					</view>
				</view>
				<view class="tags">
					<text class="tag text-center ml-2 mb-1 rounded-md"
							v-for="(item, index) in category.list" :key="index"
						@click="selectCategory(item)"
						:class="{
							active: note.category.indexOf(item.id) != -1
						}"
					>
						{{item.name}}
					</text>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import editorHeader from "./cpn/header.vue";
	import {
		mapState
	} from 'vuex'
	import {
		categoryAll
	} from "@/api/category.js";
	import {
		mutiUploadFile
	} from "@/utils/file.js";
	import {
		chooseImage
	} from "@/utils/tools.js";
	import {
		mergeBackPath
	} from "@/utils/file.js";
	import {
		deleteFile
	} from "@/api/file.js";
	import {
		editArticle
	} from "@/api/article.js";

	
	export default {
		components: {
			editorHeader
		},
		data() {
			return {
				note: {
					title: "",
					content: "",
					cover: "",
					category: [],
					pictures: []
				},
				// 弹窗
				modal: {
					showModal: false,
					title: '是否保存到草稿箱?',
					cancelColor: 'red',
					text: '',
					errorShow: false
				},
				category: {
					list: [],
					show: false
				},
				draft_index: -1,
				draft_name: null
			};
		},
		computed: {
			...mapState({
				info: state => state.user.info
			}),
			selectCategoryList() {
				let arr = [];
				this.category.list.forEach(item => {
					if(this.note.category.indexOf(item.id) != -1) arr.push(item);
				})
				return arr;
			},
			uploadedImageList() {
				return this.note.pictures.map(item => {
					return mergeBackPath(item);
				})
			},
			coverPath() {
				return mergeBackPath(this.note.cover)
			}
		},
		onLoad(options) {
			// 当是草稿箱跳转过来时
			if(options.id) {
				this.draft_index = options.id;
				//获取该用户的草稿箱
				let drafts = this.$cache.get("drafts_" + this.info.id);
				// 判断是否存在草稿箱且存在该索引下的数据时再赋值
				if(drafts && drafts[this.draft_index]) {
					this.note = drafts[this.draft_index].note;
					this.draft_name = drafts[this.draft_index].name;
				}
			}
			
			this.getAllCategory();
		},
		methods: {
			// 点击图片，弹窗
			picTap(item, index) {
				uni.showActionSheet({
					itemList: ["预览该图片", "设为封面", "删除该图片"],
					success: res => {
						// 预览图片
						if(res.tapIndex == 0) this.previewImage(index);
						// 设为封面
						if(res.tapIndex == 1) this.note.cover = this.note.pictures[index];
						// 删除图片
						if(res.tapIndex == 2) this.deleteFile(index);
						
					},
					fail: res => {
						console.log(res.errMsg);
					}
				});
			},
			// 预览图片
			previewImage(index) {
				uni.previewImage({
					urls: this.uploadedImageList,
					current: index,
					success: () => {
						console.log("成功")
					}
				})
			},
			// 返回事件
			back() {
				const feedback = this.checkArticle(true);
				// 当全部通过则说明作者写了东西，需要保存到本地
				if(this.note.cover != "" || this.note.category.length != 0 || this.note.title != "" || this.note.content != "" || this.note.pictures != "") {
					// 当是草稿箱跳转过来的时候要还原草稿箱名字
					if(this.draft_name) this.modal.text = this.draft_name;
					this.modal.showModal = true;
					
				}
				else this.$go(null, null, "navigateBack");					
			},
			// 取消保存草稿
			cancel() {
				this.modal.showModal = false;
				this.$go(null, null, "navigateBack");
			},
			// 弹框提示是否出现
			inputChange() {
				if(this.modal.text != '') this.modal.errorShow = false;
				else this.modal.errorShow = true;
			},
			// 确定
			confirm() {
				if(this.modal.text == '') {
					this.modal.errorShow = true;
					return;
				}
				
				this.modal.showModal = false;
				const draftsName = "drafts_" + this.$store.state.user.uid;
				// 获取原有的草稿箱cache
				let drafts = this.$cache.get(draftsName);
				// 存一个时间
				const draftsContent = {
					name: this.modal.text,
					note: this.note,
					time: new Date().getTime()
				}
				// 当原来不存在草稿时
				if(!drafts) this.$cache.set(draftsName, [draftsContent]);
				else {
					// 当是从草稿箱跳转过来的时候，直接替换原来的草稿箱即可
					if(this.draft_index != -1 && this.draft_name) {
						drafts[this.draft_index] = draftsContent;
					}else{
						drafts.push(draftsContent);
					}
					this.$cache.set(draftsName, drafts);
				}
				// 清空掉输入框的内容
				this.modal.text = '';
				this.$go(null, null, "navigateBack");
			},
			// 获取全部分类
			getAllCategory(pageInfo) {
				categoryAll(pageInfo).then(res => {
					this.category.list = res.category;
				}).catch(err => this.$msg(err.message));
			},
			// 选择分类
			selectCategory(value) {
				// 当已经选了该元素则删除该元素
				const index = this.note.category.indexOf(value.id);
				if(index != -1) this.note.category.splice(index, 1);
				else this.note.category.push(value.id);
			},
			// 选择图片
			chooseIamge() {
				chooseImage().then(res => {
					this.note.pictures = [...this.note.pictures, ...res];
					// 当封面不存在时，则设置封面为第一张图片
					if(this.note.cover == "") this.note.cover = res[0];
					
				}).catch(err => {
					console.log(err);
					this.$msg("选择图片失败！");
				})
			},
			deleteFile(index) {
				deleteFile({path: this.note.pictures[index]}).then(res => {
					this.note.pictures.splice(index, 1);
					// 当删除的图片是封面时
					const coverIndex = this.note.pictures.indexOf(this.note.cover);
					if(coverIndex == -1) {
						// 当没有全部删除图片时
						if(this.note.pictures.length != 0) this.note.cover = this.note.pictures[0];
						// 当全部图片都被删除时
						else this.note.cover = "";
					}
					this.$msg("文件删除成功！");
				}).catch(err => this.$msg(err.message));
			},
			// 检查文章
			checkArticle(bol = false) {
				if(this.note.cover == "") return {ok: false, message: '文章封面不能为空！'};
				if(this.note.title == "") return {ok: false, message: "文章标题不能为空！"};
				if(this.note.content == "") return {ok: false, message: "文章内容不能为空！"};				
				if(this.note.category.length == 0) return {ok: false, message: '文章分类不能为空！'};
				if(bol && this.note.pictures.length == 0) return {ok: false, message: '文章图片组不能为空！'};
				return {ok: true}
			},
			// 提交文章
			submit() {
				// 检查文章内容
				const feedback = this.checkArticle();
				if(!feedback.ok) return this.$msg(feedback.message);

				editArticle({
					type: 1,
					...this.note
				}).then(res => {
					this.$msg("文章上传成功！");
					this.$go("/pages/index/index");
				}).catch(err => this.$msg(err.message));
			}
		}
	}
</script>

<style lang="scss">
.editor{
	.content{
		.ablum{
			overflow-x: scroll;
			overflow-y: hidden;
			// padding-bottom: 10rpx;
			height: 180rpx;
			/* #ifdef H5 */
			padding-bottom: 7rpx;
			&::-webkit-scrollbar {
				width: 5px;             
				height: 5px;
			}
			&::-webkit-scrollbar-track {
				background: #d9d9d9;      
			}
			&::-webkit-scrollbar-thumb {
				  background-color: #6b6b6b;    
				  border-radius: 5px;     
				  border: 1px solid #d9d9d9;  
			}
			/* #endif */
			.block{
				min-width: 160rpx;
				margin-left: 10rpx;
				width: 160rpx;
				padding: 0;
				.tag{
					float: right;
					background-color: red;
					padding: 5rpx 15rpx;
					font-size: 25rpx;
					z-index: 10;
					border-radius: 20rpx 0 0 20rpx;
					color: white;
					/* #ifdef APP-PLUS */
					margin-bottom: -45rpx;
					/* #endif */
					/* #ifndef APP-PLUS */
					margin-bottom: -40rpx;
					/* #endif */
				}
				.img{
					min-width: 160rpx;
					width: 160rpx;
					height: 160rpx;
					margin-bottom: -9rpx;
					z-index: -1;
				}
				.img_nomal{
					min-width: 160rpx;
					width: 160rpx;
					height: 170rpx;
				}
			}
			.cover{
				border: 6rpx solid red;
				margin-left: 10rpx;
				height: 162rpx;
			}
			.add{
				min-width: 160rpx;
				width: 160rpx;
				height: 170rpx;
				margin-left: 10rpx;
			}
			.add{
				font-size: 80rpx;
				font-weight: bold;
				background-color: rgba(#6f6f6f, .12);
				color: #9e9e9e;
			}
		}
		.title{
			border-bottom: 1rpx solid rgba(#6f6f6f, .18);
		}
		.content{
			min-height: 400rpx;
			border-bottom: 1rpx solid rgba(#6f6f6f, .18);
		}
		.category{
			color: #8d8d8d;
			font-size: 25rpx;
			&_title{
				.select{
					overflow: hidden;
					.left{
						float: left;
					}
					.right{
						float: right;
					}
				}
				.tags{
					.tag{
						color: #363636;
					}
				}
			}
		}
	}
	.slot-content{
		.error{
			color: red;
			font-size: 25rpx;
		}
	}
	.popup{
		.close{
			overflow: hidden;
			.icon{
				float: right;	
			}
		}
		.tags{
			.tag{
				min-width: 100rpx;
				padding: 7rpx 0rpx;
				float: left;
				color: #8d8d8d;
			}
			.active{
				background-color: #71e7ba;
				color: #363636;
			}
		}
	}
}
</style>
